﻿using System;
using System.Net;
using static CatUtils.Utils.Currency.PrintLog;

namespace CatUtilsDll.Utils.Currency.WebUtils
{/// <summary>
 /// 网络请求帮助
 /// </summary>
    public partial class WebHelper
    {
        /// <summary>
        /// 写入WebLog
        /// </summary>
        /// <param name="RequestUrl"></param>
        /// <param name="ex"></param>
        private static void PrintWebLog(string RequestUrl, Exception ex)
        {
            PrintChinesLog($"错误链接：{RequestUrl}\r\n{ex.ToString()}", ErrorTypeName.WebError);
        }

        /// <summary>
        /// 获取网址包含的主域名
        /// </summary>
        /// <param name="RequestUrl"></param>
        /// <returns></returns>
        public string GetHost(string RequestUrl)
        {
            try
            {
                return new Uri(RequestUrl).Host;
            }
            catch (Exception ex)
            {
                PrintWebLog(RequestUrl, ex);
            }
            return "";
        }

        /// 创建HTTPRequest
        /// </summary>
        /// <param name="RequestUrl"></param>
        /// <param name="AllowAutoRedirect">是否跟随重定向</param>
        /// <returns></returns>
        private static HttpWebRequest CreateHttpRequest(string RequestUrl, bool AllowAutoRedirect)
        {
            try
            {
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(RequestUrl);

                httpReq.Host = new Uri(RequestUrl).Host;
                httpReq.AllowAutoRedirect = AllowAutoRedirect;//这里很重要，如果你跟随和不跟随重定向得到的结果不同，由于我项目需要跟随重定向，故已经跟随。如果不需要请改为false
                httpReq.UserAgent = UserAgentPC;
                return httpReq;
            }
            catch (Exception ex)
            {
                PrintWebLog(RequestUrl, ex);
            }
            return null;
        }
    }
}